<template>
  <div class="report-form-content">
    <el-form class="my-form"
             ref="objForm"
             :model="obj"
             :rules="rules"
             label-position="right"
             label-width="auto"
             label-suffix="：">
      <div class="tabs-form-head">
        <span>合同验收</span>
        <div class="">
          <el-button type="primary" plain @click="returnBtn">取消</el-button>
        </div>
      </div>
      <el-divider border-style="dashed" />
      <el-row :gutter="20">
        <el-col :sm="24" :lg="24" style="padding-left: 20px">
          <el-card class="update-log">
              <span class="file-list-btn-span">*温馨提示:保存成功后才能预览word文档和Excel报表</span>
            <el-table :data="objList"
                      style="width: 100%; margin-top: 20px"
                      row-key="id"
                      border
                      default-expand-all>
              <el-table-column label="内容/负责人"  width="200px">
                <template v-slot="{row}">
                  <el-form-item label="内容">
                    <span>{{ row.content }}</span>
                  </el-form-item>
                  <el-form-item label="负责人">
                    <LabelTag :foreignList="userList" :foreignIds="row.principalUserId" :foreignLabel="'name'" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="监理/验收时间/验收意见/审批方式" width="400px">
                <template v-slot="{row}">
                  <el-form-item prop="supervisorUserId" label="监理" class="margin-bottom5">
                    <User v-model="row.supervisorUserId" keyName="id" keyShow="name" placeholder="监理" title="用户查询" />
                  </el-form-item>
                  <el-form-item prop="checkingTime" label="验收时间" class="margin-bottom5">
                    <el-date-picker v-model="row.checkingTime" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
                  </el-form-item>
                  <el-form-item prop="checkingComment" label="验收意见" class="margin-bottom5">
                    <el-input v-model="row.checkingComment" placeholder="验收意见" />
                  </el-form-item>
                  <el-form-item prop="approvalType" label="审批方式" class="margin-bottom5">
                    <el-radio-group v-model="row.approvalType">
                      <el-radio label="1">线上审批</el-radio>
                      <el-radio label="2">线下审批</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="验收状态" width="100">
                <template v-slot="{row}">
                  <EnumTag :enum-list="getDictList('ContractInitialCheckingState')" :enum-key="row.state" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="验收附件" width="400px">
                <template v-slot="scope">
                  <div style="display: flex;justify-content: center;">
                    <el-button type="primary" plain style="margin-right:1rem;" @click="selectAttachmentBtn(scope.row, scope.$index, '01')"><svg-icon icon-class="search" />选择已上传的文件</el-button>
                    <FileUpload :isShowTip="false" v-model="attachmentFiles" :isShowFileList="false" @uploadedSuccess="UploadedSuccessFn($event, objList, scope.$index, '01')" />
                  </div>
                  <ul class="files-url">
                    <li class="files-green" v-for="(item1, idx) in scope.row.attachments" :key="item1.id" v-show="item1.attachmentType === '01'">
                      <div class="file-text" v-if="item1.attachmentType === '01'">
                        <div>
                          <span class="file-name">{{ item1.attachmentName }}</span>
                          <span class="file-kb">{{ bytesToSize(item1.attachmentSize) }}</span>
                        </div>
                        <div>
                          <span class="file-time">{{ showIdLabel(userList, item1.attachmentUploader, 'name') }}<span style="color:#333;">上传于</span>{{ item1.attachmentUpload }}</span>
                        </div>
                      </div>
                      <div class="file-btn">
                        <el-button type="primary" link @click="downloadFile(item1)">下载</el-button>
                        <el-button type="primary" link @click="handlePreview(item1)">预览</el-button>
                        <el-button type="danger" link @click="deleteBtn(objList.value, scope.$index, idx)">删除</el-button>
                      </div>
                    </li>
                  </ul>
                </template>
              </el-table-column>
              <el-table-column align="center" label="签名/盖章附件" width="400px">
                <template v-slot="scope">
                  <div style="display: flex;justify-content: center;">
                    <el-button type="primary" plain style="margin-right:1rem;" @click="selectAttachmentBtn(scope.row, scope.$index, '02')" :disabled="scope.row.approvalType !== '2'"><svg-icon icon-class="search" />选择已上传的文件</el-button>
                    <FileUpload :isShowTip="false" v-model="attachmentFiles" :isShowFileList="false" @uploadedSuccess="UploadedSuccessFn($event, objList, scope.$index, '02')" :disabled="scope.row.approvalType !== '2'" />
                  </div>
                  <ul class="files-url">
                    <li class="files-green" v-for="(item1, idx) in scope.row.attachments" :key="item1.id" v-show="item1.attachmentType === '02'">
                      <div class="file-text">
                        <div>
                          <span class="file-name">{{ item1.attachmentName }}</span>
                          <span class="file-kb">{{ bytesToSize(item1.attachmentSize) }}</span>
                        </div>
                        <div>
                          <span class="file-time">{{ showIdLabel(userList, item1.attachmentUploader, 'name') }}<span style="color:#333;">上传于</span>{{ item1.attachmentUpload }}</span>
                        </div>
                      </div>
                      <div class="file-btn">
                        <el-button type="primary" link @click="downloadFile(item1)">下载</el-button>
                        <el-button type="primary" link @click="handlePreview(item1)">预览</el-button>
                        <el-button type="danger" link @click="deleteBtn(objList.value, scope.$index, idx)">删除</el-button>
                      </div>
                    </li>
                  </ul>
                </template>
              </el-table-column>
              <el-table-column align="center" label="验收结果附件" width="400px">
                <template v-slot="scope">
                  <div style="display: flex;justify-content: center;">
                    <el-button type="primary" plain style="margin-right:1rem;" @click="selectAttachmentBtn(scope.row, scope.$index, '03')"><svg-icon icon-class="search" />选择已上传的文件</el-button>
                    <FileUpload :isShowTip="false" v-model="attachmentFiles" :isShowFileList="false" @uploadedSuccess="UploadedSuccessFn($event, objList, scope.$index, '03')" />
                  </div>
                  <ul class="files-url">
                    <li class="files-green" v-for="(item1, idx) in scope.row.attachments" :key="item1.id" v-show="item1.attachmentType === '03'">
                      <div class="file-text">
                        <div>
                          <span class="file-name">{{ item1.attachmentName }}</span>
                          <span class="file-kb">{{ bytesToSize(item1.attachmentSize) }}</span>
                        </div>
                        <div>
                          <span class="file-time">{{ showIdLabel(userList, item1.attachmentUploader, 'name') }}<span style="color:#333;">上传于</span>{{ item1.attachmentUpload }}</span>
                        </div>
                      </div>
                      <div class="file-btn">
                        <el-button type="primary" link @click="downloadFile(item1)">下载</el-button>
                        <el-button type="primary" link @click="handlePreview(item1)">预览</el-button>
                        <el-button type="danger" link @click="deleteBtn(objList.value, scope.$index, idx)">删除</el-button>
                      </div>
                    </li>
                  </ul>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="150px" fixed="right">
                <template v-slot="{row}">
                  <el-button type="primary" v-if="['0','3','4'].includes(row.state)" @click="handleSubmit(row)">提交验收</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog v-model="attachmentVisible" title="附件预览" width="70%" top="2vh">
      <attachmentPreview v-model:attachmentId="previewAttachmentId" />
      <div style="text-align:right;">
        <el-button type="danger" @click="attachmentVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="selectAttachmentVisible" title="选择文件" width="70%" top="2vh">
      <selectAttachmentMultiple :isVisible="selectAttachmentVisible" @selectAttachment="selectAttachmentFn" @close="selectAttachmentVisible = false"></selectAttachmentMultiple>
    </el-dialog>
    <selectApprove v-model:itemsVisible="dialogApproveVisible" @close="dialogApproveVisible = false" :business="'3007'" :businessId="obj.id" @doSubmit="doSubmit" />
  </div>
</template>
<script setup>
import {getCurrentInstance, ref} from 'vue'
import {doGet, doGetDownload, doPost} from "@/config/http";
import {
  svc,
  showIdLabel,
  getListPageSize,
  bytesToSize,
  notifySuccess,
  alertErrorMsg,
  isNullOrUndefinedOrEmpty,
  getDictList
} from "@/config/common";
import selectAttachmentMultiple from '@/views/components/base/selectAttachmentMultiple.vue'
import attachmentPreview from '@/views/components/base/attachmentPreview.vue'
import { useRoute } from 'vue-router'
import SvgIcon from "@/components/SvgIcon/index.vue";
import selectApprove from "@/views/components/base/selectApprove.vue";
import User from "@/views/components/base/selectUser.vue";
import {getUserId} from "@/config/cookie";
import useUserStore from "@/store/modules/user";
import initListStore from '@/store/modules/initList'

const route = useRoute()

const { proxy: ctx } = getCurrentInstance();

let obj = ref({
  contractInitialId: route.query.id, // 合同ID
  batch: null, // 批次号
  contractInitialInspectionId: null, // 合同验收条件表ID
  content: null, // 验收内容
  principalUserId: null, // 验收负责人用户ID
  supervisorUserId: null, // 监理人用户ID
  checkingTime: null, // 验收时间
  state: null, // 验收状态
  checkingComment: null, // 验收意见
  checkingAttachmentId: null, // 附件
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
})

let selectedItem = ref(null)

let objForm = ref(null)
let dialogApproveVisible = ref(false)

let currentData = ref({
  row: null,
  index: null,
  type: null
})

let objList = ref([])

let attachmentFiles = ref()

let attachmentVisible = ref(false)
let previewAttachmentId = ref('')
let selectAttachmentVisible = ref(false)

// let contractTypeList = ref([]) // 合同类型
// let contractCooperationList = ref([]) // 往来单位
// let contractFeetypeList = ref([]) // 合同费用类型
// let contractTemplateList = ref([]) // 合同模版
// let bankList = ref([]) // 银行
let userList = initListStore().userList // 用户
// let governmentList = ref([]) //  政府单位
// let organizationList = ref([]) // 部门
// let contractSignerList = ref([]) // 签订人
// let contractFiletypeList = ref([]) // 合同附件类型

const rules = {}

// const initList = async () => {
//   let p1 = doGet(svc, '/contract-type/page', {pageSize: getListPageSize()}, false) // 合同类型
//   let p2 = doGet(svc, '/contract-cooperation/page', {pageSize: getListPageSize()}, false) // 往来单位
//   let p3 = doGet(svc, '/contract-feetype/page', {pageSize: getListPageSize()}, false) // 合同费用类型
//   let p4 = doGet(svc, '/contract-template/page', {pageSize: getListPageSize()}, false) // 合同模版
//   let p5 = doGet(svc, '/bank/page', {pageSize: getListPageSize()}, false) // 银行
//   let p6 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false) // 用户
//   let p7 = doGet(svc, '/government/page', {pageSize: getListPageSize()}, false) //  政府单位
//   let p8 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false) // 部门
//   let p9 = doGet(svc, '/contract-signer/page', {pageSize: getListPageSize()}, false) // 签订人
//   let p10 = doGet(svc, '/contract-filetype/page', {pageSize: getListPageSize()}, false) // 合同附件类型
//   let resArray = await Promise.all([p1, p2, p3, p4, p5, p6, p7, p8, p9, p10])
//   contractTypeList.value = resArray[0]['records']
//   contractCooperationList.value = resArray[1]['records']
//   contractFeetypeList.value = resArray[2]['records']
//   contractTemplateList.value = resArray[3]['records']
//   bankList.value = resArray[4]['records']
//   userList.value = resArray[5]['records']
//   governmentList.value = resArray[6]['records']
//   organizationList.value = resArray[7]['records']
//   contractSignerList.value = resArray[8]['records']
//   contractFiletypeList.value = resArray[9]['records']
// }

const initObj = async () =>  {
  if (route.query.id) {
    obj.value = await doGet(svc, `/contract-initial/${route.query.id}`, {}, true)
    // 验收条件
    let listQuery = {
      contractInitialId: route.query.id,
      batch: 'latest',
      pageNum: 1,
      pageSize: 1000,
    }
    let res = await doGet(svc, '/contract-initial-checking/page', listQuery, true)
    let res1 = await doGet(svc, '/contract-initial-checking-attachment/page', listQuery, false)
    if (res && res1) {
      objList.value = res.records
      let files = res1.records
      if (files.length > 0) {
        objList.value = objList.value.map((item) => {
          item.attachments = []
          files.map(item1 => {
            if (item.id === item1.contractInitialCheckingId) {
              item.attachments.push(item1)
            }
          })
          return item
        })
      }
    }
  }
}

// initList()
initObj()

// 已上传文件
const selectAttachmentBtn = (row,index,type) => {
  selectAttachmentVisible.value = true
  currentData.value.row = row
  currentData.value.index = index
  currentData.value.type = type
}

const selectAttachmentFn = (list) => {
  list.map(item => {
    UploadedSuccessFn(item, objList.value, currentData.value.index, currentData.value.type)
  })
}

const UploadedSuccessFn = (file, arr, index, type) => {
  let filesObj = {
    attachmentId: file.attachmentId ? file.attachmentId : file.id, // 附件ID
    attachmentName: file.file ? file.file.name : file.fileName, // 附件名称
    attachmentType: type, // 附件类型
    attachmentUrl: file.url ? file.url : '',	//附件URL		false
    attachmentSize: file.size ? file.size : file.fileSize, //附件大小
    attachmentUpload: file.createTime, //附件上传时间
    attachmentUploader: file.updateBy, //附件上传人
    contractInitialCheckingId: arr[index].id, // 初始合同验收ID
    createBy: '', // 创建人用户ID
    createTime: '', // 创建时间
    id: '', // 主键ID
    updateBy: '', // 最后修改人用户ID
    updateTime: '', // 最后修改时间
    version: '', // 数据版本
  }
  if (!arr[index].attachments) {
    arr[index].attachments = []
  }
  arr[index].attachments.push(filesObj)
}

const downloadFile = (row) => {
  doGetDownload(svc, `/customAttachment/download/${row.attachmentId}`, {})
}
const handlePreview = (file) => {
  attachmentVisible.value = true
  setTimeout(() => {
    previewAttachmentId.value = file.attachmentId
  },100)
}
const deleteBtn = (arr, index, idx) => {
  arr[index].attachments.splice(idx, 1)
}

const handleSubmit = async (row) => {
  if (isNullOrUndefinedOrEmpty(row.supervisorUserId)) {
    alertErrorMsg('监理人不能为空。')
    return
  }
  if (isNullOrUndefinedOrEmpty(row.checkingTime)) {
    alertErrorMsg('验收时间不能为空。')
    return
  }
  if (isNullOrUndefinedOrEmpty(row.approvalType)) {
    alertErrorMsg('审批方式不能为空。')
    return
  }
  selectedItem.value = row
  switch (row.approvalType) {
    case "1":
      dialogApproveVisible.value = true
      break;
    case "2":
      await doSubmit(row)
      break;
  }
}

const doSubmit = async (data) => {
  let v = await objForm.value.validate().catch((err)=>{return err})
  if (v !== true) {
    alertErrorMsg('表单验证不通过，请检查数据。')
    return
  }
  selectedItem.value.cashUserId = getUserId()
  selectedItem.value.cashDepartmentId = useUserStore().organization.id;
  let o = {}
  o.oper = 'update'
  o.approveId = data.approveId
  o.approveNodes = data.approveNodes
  o.items = [selectedItem.value]
  doPost(svc, `/customContractInitial/checkingContractInitial/${route.query.id}`, o, true).then(() => {
    notifySuccess('提交成功')
    returnBtn()
  })
}

const returnBtn = () => {
  switch (route.query.kind) {
    case '1':
      ctx.goTargetByName('contractInitial', {});
      break;
    case '2':
      ctx.goTargetByName('contractMain', {})
      break;
  }
}
</script>
<style scoped>
.margin-bottom5 {
  margin-bottom: 5px;
}
.report-form-content {
  padding: 20px;
}
.update-log {
  width: 100%;
  margin: 30px 0;
}
.tabs-form-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.tabs-form-head span {
  font-size: 18px;
  color: #303133;
  font-weight: bold;
}
.files-url {
  list-style-type: none;
  margin: 0;
  padding: 0;
  text-align: left;
}
.files-url li {
  list-style-type: none;
  margin: 5px;
  padding: 0;
}
.files-url li.files-green {
  border: 1px solid #1ab394;
  background-color: #eaffea;
}
.files-url li.files-red {
  border: 1px solid #F56C6C;
  background-color: #fcf3f3;
}
.files-url li {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 5px 10px;
}
.files-url li span {
  padding: 0 5px;
  font-size: 12px;
  font-weight: bold;
}
.update-log {
  width: 100%;
  margin: 30px 0;
}
.file-list-btn-span {
  color: #F56C6C;
  font-size: 12px;
}
</style>
